package com.caigou.modules.rank.ui.fans

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseFragment
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.date2ts
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.utils.ImageLoader
import com.caigou.comm.base.viewmodel.FollowViewModel
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.rank.R
import com.caigou.modules.rank.adapter.FansRankItemAdapter
import com.caigou.modules.rank.bean.FansRankBean
import com.caigou.modules.rank.bean.FansRankItemBean
import com.caigou.modules.rank.databinding.FragmentMonthFansRankBinding
import com.caigou.modules.rank.ext.countDownCoroutines
import com.caigou.modules.rank.viewmodel.RankViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Job
import java.text.SimpleDateFormat
import java.util.*

/**
 * @author #Suyghur.
 * Created on 2021/11/05
 */
@AndroidEntryPoint
class MonthFansRankFragment : BaseFragment() {

    private var _binding: FragmentMonthFansRankBinding? = null
    private val binding get() = _binding!!

    private val rankViewModel: RankViewModel by viewModels()
    private val followViewModel: FollowViewModel by viewModels()

    private var headerList = mutableListOf<FansRankItemBean>()

    private var currentYear: String = ""
    private var currentMonth: String = ""

    /**
     * RecyclerView Divider
     */
    private val recyclerViewItemDecoration by lazy {
        SpaceItemDecoration(requireActivity())
    }

    private val linearLayoutManager: LinearLayoutManager by lazy {
        LinearLayoutManager(requireActivity())
    }

    private val mAdapter: FansRankItemAdapter by lazy {
        FansRankItemAdapter(mutableListOf())
    }

    private var countDownJob: Job? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentMonthFansRankBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun initView() {
        binding.monthFansRankSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                rankViewModel.getFansRank("$currentYear-$currentMonth", AppBackgroundInfo.instance.userBean!!.userId)
            }
        }

        binding.monthFansRankRecyclerView.run {
            layoutManager = linearLayoutManager
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(recyclerViewItemDecoration)
        }

        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            val item = mAdapter.getItem(position)
            when (view.id) {
                R.id.item_fans_rank_iv_avatar -> {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, item.userId)
                        .navigation()
                }
                R.id.item_fans_rank_btn_follow -> {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, item.userId)
                }
            }
        }

        binding.monthFansRankIvAvatar.setOnClickListener {
            ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                .withString(AppConstants.USER_ID, AppBackgroundInfo.instance.userBean!!.userId)
                .navigation()
        }

        val calendar = Calendar.getInstance()
        calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE))
        val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        val date = "${sdf.format(calendar.time)} 23:59:59"
        val ts = date2ts(date)
        countDownJob = countDownCoroutines(ts, lifecycleScope, onTick = { time ->
            binding.monthFansRankTvCountDown.text = time
        }, null, null)
    }

    override fun lazyLoad() {
        currentYear = Calendar.getInstance().get(Calendar.YEAR).toString()
        val month = Calendar.getInstance().get(Calendar.MONTH) + 1
        currentMonth = if (month == 13) {
            "1"
        } else {
            month.toString()
        }
        rankViewModel.getFansRank("$currentYear-$currentMonth", AppBackgroundInfo.instance.userBean!!.userId)
    }

    override fun onBack() {
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(rankViewModel.fansRankViewModel, ::handleGetFansRank)
        observe(followViewModel.followLiveData, ::handleSetFollow)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
        countDownJob?.cancel()
    }

    fun refreshData(date: String) {
        rankViewModel.getFansRank(date, AppBackgroundInfo.instance.userBean!!.userId)
    }

    private fun handleLadder() {
        when (headerList.size) {
            1 -> {
                binding.monthFansRankLayoutLadder.ladderTvNickname1.text = headerList[0].nickName
                binding.monthFansRankLayoutLadder.ladderTvNum1.text = headerList[0].fansCount.toString()
                if (TextUtils.isEmpty(headerList[0].headImg)) {
                    binding.monthFansRankLayoutLadder.ladderIvAvatar1.setImageResource(R.drawable.img_comm_avatar)
                } else {
                    ImageLoader.loadCircle(requireActivity(), headerList[0].headImg, binding.monthFansRankLayoutLadder.ladderIvAvatar1)
                }
                if (headerList[0].concern) {
                    binding.monthFansRankLayoutLadder.ladderBtnFollow1.setBackgroundResource(R.drawable.comm_btn_gray2)
                    binding.monthFansRankLayoutLadder.ladderBtnFollow1.text = "已关注"
                } else {
                    binding.monthFansRankLayoutLadder.ladderBtnFollow1.setBackgroundResource(R.drawable.comm_btn_red2)
                    binding.monthFansRankLayoutLadder.ladderBtnFollow1.text = "+关注"
                }

                binding.monthFansRankLayoutLadder.ladderIvAvatar1.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, headerList[0].userId)
                        .navigation()
                }

                binding.monthFansRankLayoutLadder.ladderBtnFollow1.setOnClickListener {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, headerList[0].userId)
                }

            }
            2 -> {
                binding.monthFansRankLayoutLadder.ladderTvNickname1.text = headerList[0].nickName
                binding.monthFansRankLayoutLadder.ladderTvNum1.text = headerList[0].fansCount.toString()
                if (TextUtils.isEmpty(headerList[0].headImg)) {
                    binding.monthFansRankLayoutLadder.ladderIvAvatar1.setImageResource(R.drawable.img_comm_avatar)
                } else {
                    ImageLoader.loadCircle(requireActivity(), headerList[0].headImg, binding.monthFansRankLayoutLadder.ladderIvAvatar1)
                }
                if (headerList[0].concern) {
                    binding.monthFansRankLayoutLadder.ladderBtnFollow1.setBackgroundResource(R.drawable.comm_btn_gray2)
                    binding.monthFansRankLayoutLadder.ladderBtnFollow1.text = "已关注"
                } else {
                    binding.monthFansRankLayoutLadder.ladderBtnFollow1.setBackgroundResource(R.drawable.comm_btn_red2)
                    binding.monthFansRankLayoutLadder.ladderBtnFollow1.text = "+关注"
                }

                binding.monthFansRankLayoutLadder.ladderTvNickname2.text = headerList[1].nickName
                binding.monthFansRankLayoutLadder.ladderTvNum2.text = headerList[1].fansCount.toString()
                if (TextUtils.isEmpty(headerList[1].headImg)) {
                    binding.monthFansRankLayoutLadder.ladderIvAvatar2.setImageResource(R.drawable.img_comm_avatar)
                } else {
                    ImageLoader.loadCircle(requireActivity(), headerList[1].headImg, binding.monthFansRankLayoutLadder.ladderIvAvatar2)
                }
                if (headerList[0].concern) {
                    binding.monthFansRankLayoutLadder.ladderBtnFollow2.setBackgroundResource(R.drawable.comm_btn_gray2)
                    binding.monthFansRankLayoutLadder.ladderBtnFollow2.text = "已关注"
                } else {
                    binding.monthFansRankLayoutLadder.ladderBtnFollow2.setBackgroundResource(R.drawable.comm_btn_red2)
                    binding.monthFansRankLayoutLadder.ladderBtnFollow2.text = "+关注"
                }

                binding.monthFansRankLayoutLadder.ladderIvAvatar1.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, headerList[0].userId)
                        .navigation()
                }

                binding.monthFansRankLayoutLadder.ladderIvAvatar2.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, headerList[1].userId)
                        .navigation()
                }

                binding.monthFansRankLayoutLadder.ladderBtnFollow1.setOnClickListener {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, headerList[0].userId)
                }

                binding.monthFansRankLayoutLadder.ladderBtnFollow2.setOnClickListener {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, headerList[1].userId)
                }
            }
            3 -> {
                binding.monthFansRankLayoutLadder.ladderTvNickname1.text = headerList[0].nickName
                binding.monthFansRankLayoutLadder.ladderTvNum1.text = headerList[0].fansCount.toString()
                if (TextUtils.isEmpty(headerList[0].headImg)) {
                    binding.monthFansRankLayoutLadder.ladderIvAvatar1.setImageResource(R.drawable.img_comm_avatar)
                } else {
                    ImageLoader.loadCircle(requireActivity(), headerList[0].headImg, binding.monthFansRankLayoutLadder.ladderIvAvatar1)
                }
                if (headerList[0].concern) {
                    binding.monthFansRankLayoutLadder.ladderBtnFollow1.setBackgroundResource(R.drawable.comm_btn_gray2)
                    binding.monthFansRankLayoutLadder.ladderBtnFollow1.text = "已关注"
                } else {
                    binding.monthFansRankLayoutLadder.ladderBtnFollow1.setBackgroundResource(R.drawable.comm_btn_red2)
                    binding.monthFansRankLayoutLadder.ladderBtnFollow1.text = "+关注"
                }

                binding.monthFansRankLayoutLadder.ladderTvNickname2.text = headerList[1].nickName
                binding.monthFansRankLayoutLadder.ladderTvNum2.text = headerList[1].fansCount.toString()
                if (TextUtils.isEmpty(headerList[1].headImg)) {
                    binding.monthFansRankLayoutLadder.ladderIvAvatar2.setImageResource(R.drawable.img_comm_avatar)
                } else {
                    ImageLoader.loadCircle(requireActivity(), headerList[1].headImg, binding.monthFansRankLayoutLadder.ladderIvAvatar2)
                }
                if (headerList[0].concern) {
                    binding.monthFansRankLayoutLadder.ladderBtnFollow2.setBackgroundResource(R.drawable.comm_btn_gray2)
                    binding.monthFansRankLayoutLadder.ladderBtnFollow2.text = "已关注"
                } else {
                    binding.monthFansRankLayoutLadder.ladderBtnFollow2.setBackgroundResource(R.drawable.comm_btn_red2)
                    binding.monthFansRankLayoutLadder.ladderBtnFollow2.text = "+关注"
                }

                binding.monthFansRankLayoutLadder.ladderTvNickname3.text = headerList[2].nickName
                binding.monthFansRankLayoutLadder.ladderTvNum3.text = headerList[2].fansCount.toString()
                if (TextUtils.isEmpty(headerList[2].headImg)) {
                    binding.monthFansRankLayoutLadder.ladderIvAvatar3.setImageResource(R.drawable.img_comm_avatar)
                } else {
                    ImageLoader.loadCircle(requireActivity(), headerList[2].headImg, binding.monthFansRankLayoutLadder.ladderIvAvatar3)
                }
                if (headerList[0].concern) {
                    binding.monthFansRankLayoutLadder.ladderBtnFollow3.setBackgroundResource(R.drawable.comm_btn_gray2)
                    binding.monthFansRankLayoutLadder.ladderBtnFollow3.text = "已关注"
                } else {
                    binding.monthFansRankLayoutLadder.ladderBtnFollow3.setBackgroundResource(R.drawable.comm_btn_red2)
                    binding.monthFansRankLayoutLadder.ladderBtnFollow3.text = "+关注"
                }

                binding.monthFansRankLayoutLadder.ladderIvAvatar1.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, headerList[0].userId)
                        .navigation()
                }

                binding.monthFansRankLayoutLadder.ladderIvAvatar2.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, headerList[1].userId)
                        .navigation()
                }

                binding.monthFansRankLayoutLadder.ladderIvAvatar3.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, headerList[2].userId)
                        .navigation()
                }

                binding.monthFansRankLayoutLadder.ladderBtnFollow1.setOnClickListener {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, headerList[0].userId)
                }

                binding.monthFansRankLayoutLadder.ladderBtnFollow2.setOnClickListener {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, headerList[1].userId)
                }

                binding.monthFansRankLayoutLadder.ladderBtnFollow2.setOnClickListener {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, headerList[2].userId)
                }

            }
        }
    }

    private fun handleGetFansRank(result: Resource<FansRankBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.monthFansRankSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取粉丝排行榜信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.monthFansRankSwipeRefreshLayout.isRefreshing = false

                if (result.data == null) {
                    return
                }

                if (TextUtils.isEmpty(result.data!!.headImg)) {
                    binding.monthFansRankIvAvatar.setImageResource(R.drawable.img_comm_avatar)
                } else {
                    ImageLoader.loadCircle(requireActivity(), result.data!!.headImg, binding.monthFansRankIvAvatar)
                }
                binding.monthFansRankTvNum.text = result.data!!.value.toString()
                binding.monthFansRankTvIndex.text = result.data!!.rank

                headerList.clear()
                val tempList = mutableListOf<FansRankItemBean>()
                for (index in 0 until result.data!!.list.size) {
                    if (index <= 2) {
                        headerList.add(result.data!!.list[index])
                    } else {
                        tempList.add(result.data!!.list[index])
                    }
                }
                mAdapter.setList(tempList)
                handleLadder()
            }
        }
    }

    private fun handleSetFollow(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("关注异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                result.data?.apply {
                    showToast(result.data!!)
                }
                rankViewModel.getFansRank("$currentYear-$currentMonth", AppBackgroundInfo.instance.userBean!!.userId)
                LiveDataBus.get().with(BusKey.REFRESH_USER_INFO).value = Any()
            }
        }
    }
}